var fs = require('fs');
var path = require('path');
var child_process = require('child_process');
var dirName = process.argv[2];
console.log('dirName ',dirName)
//https://www.cnblogs.com/meteoric_cry/p/3524193.html
//http://www.aspku.com/kaifa/javascript/10865.html
//https://www.linux-man.cn/command/pngquant
//文件名或者路径不能用空格，不能用中文
var resList = []
function pngquant(res_path) {
	var stat = fs.statSync(res_path);
	if (!stat.isDirectory()) {
		return;
	}
	var subpaths = fs.readdirSync(res_path),
		subpath;
	for (var i = 0; i < subpaths.length; ++i) {
		if (subpaths[i][0] === '.') {
			continue;
		}
		subpath = path.join(res_path, subpaths[i]);
		stat = fs.statSync(subpath);
		if (stat.isFile()) {
			if(subpath.indexOf('.meta') >= 0){
				continue
			}
			if(subpath.indexOf('.png') >= 0){
				
				resList.push(subpath)
			}
		}else if(stat.isDirectory()){
			pngquant(subpath);
		}
	}
	
	processFile();
	
}

function processFile(){
	console.log(" resList.length ",resList.length)
	if(resList.length > 0){
		let subpath = resList.shift();
		try{
				child_process.exec("pngquant.exe " + subpath + ' --force -o '+subpath+' --nofs --quality=40-80 ', function(error, stdout, stderr) {
					console.log('error',error)
					console.log('subpath ',subpath)
					processFile();
				});	
		}catch(e ){
			processFile();
		}
					
	}
		
}
if(dirName){
	pngquant(dirName)
}
module.exports.pngquant = pngquant
